/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Xml;
using System.Xml.Linq;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif

namespace Oceanside.Payments
{
    public class Debit
    {
        static string comNumStr = "1";

        static XmlDocument _baudTemplate;
        static XmlDocument _initTemplate;
        static XmlDocument _getPinTemplate;
        static XmlDocument _transactionTemplate;

        public string Amount;
        public string AccountNo;
        public string Timeout = "60";
        public string IpAddress;
        public string IpPort;
        public string InvoiceNo;
        public string Purchase;
        public string Tax;
        public string Address;
        public string Zip;
        public string CVVData;
        public string SequenceNo;
        public string Signature;
        public string TraceData;
        public string CustomerCode;
        public string PINBlock;
        public string DervdKey;
        public string CashBack = "0.00";
        public string RefNo;
        public string AuthCode;

        public override string ToString()
        {
            if (_transactionTemplate != null)
            {
                return _transactionTemplate.InnerXml;
            }
            else
            {
                return "";
            }
        }
        static Debit()
        {
            string template =
                        "<?xml version=\"1.0\"?>" +
                        "<RequestStream>" +
                        "<ComPort></ComPort>" +
                        "<Command></Command>" +
                        "</RequestStream>";

            XDocument xd = XDocument.Parse(template);
            _baudTemplate = new XmlDocument();
            _baudTemplate.LoadXml(xd.ToString());

            template =
                        "<?xml version=\"1.0\"?>" +
                        "<RequestStream>" +
                        "<ComPort></ComPort>" +
                        "<Command></Command>" +
                        "<IdlePrompt></IdlePrompt>" +
                        "</RequestStream>";

            xd = XDocument.Parse(template);
            _initTemplate = new XmlDocument();
            _initTemplate.LoadXml(xd.ToString());

            template =
                        "<?xml version=\"1.0\"?>" +
                        "<RequestStream>" +
                        "<ComPort></ComPort>" +
                        "<Command></Command>" +
                        "<AccountNo></AccountNo>" +
                        "<Amount></Amount>" +
                        "<Timeout></Timeout>" +
                        "</RequestStream>";

            xd = XDocument.Parse(template);
            _getPinTemplate = new XmlDocument();
            _getPinTemplate.LoadXml(xd.ToString());

            template =
                        "<?xml version=\"1.0\"?>" +
                        "<TStream>" +
                        "<Transaction>" +
                        "<IpAddress></IpAddress>" +
                        "<IpPort></IpPort>" +
                        "<MerchantID></MerchantID>" +
                        //"<TerminalID></TerminalID>" +
                        "<OperatorID></OperatorID>" +
                        "<Memo></Memo>" +
                        "<TranType></TranType>" +
                        "<Duplicate></Duplicate>" +
                        "<CardType></CardType>" +
                        "<TranCode></TranCode>" +
                        "<InvoiceNo></InvoiceNo>" +
                        "<RefNo></RefNo>" +
                        "<Account>" +
                        "<Track2></Track2>" +
                        "</Account>" +
                        "<Amount>" +
                        "<Purchase></Purchase>" +
                        "<CashBack></CashBack>" +
                        "</Amount>" +
                        "<PIN>" +
                        "<PINBlock></PINBlock>" +
                        "<DervdKey></DervdKey>" +
                        "</PIN>" +
                        "<SequenceNo></SequenceNo>" +
                        "<TerminalName></TerminalName>" +
                        "<ShiftID></ShiftID>" +
                        "<Signature></Signature>" +
                        "</Transaction>" +
                        "</TStream>";

            xd = XDocument.Parse(template);
            _transactionTemplate = new XmlDocument();
            _transactionTemplate.LoadXml(xd.ToString()); 
        }

        public static string Init(string com, string idlePrompt)
        {
            comNumStr = com;
            string response = null;
            try
            {
                _baudTemplate.GetElementsByTagName("ComPort")[0].InnerText = com;
                _baudTemplate.GetElementsByTagName("Command")[0].InnerText = "SetBaudRate";

                response = PaymentEngine.DebitComChan.ProcessRequest(_baudTemplate.InnerXml, PaymentEngine.CONST_NO_DIALOG);
                PinPadResponse pinResponse = new PinPadResponse();
                pinResponse.Parse(response);
                if (pinResponse.Success)
                {
                    _initTemplate.GetElementsByTagName("ComPort")[0].InnerText = com;
                    _initTemplate.GetElementsByTagName("Command")[0].InnerText = "Init";
                    _initTemplate.GetElementsByTagName("IdlePrompt")[0].InnerText = idlePrompt;

                    response = PaymentEngine.DebitComChan.ProcessRequest(_initTemplate.InnerXml, PaymentEngine.CONST_NO_DIALOG);
                    pinResponse.Parse(response);
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
                response = null;
            }
            return response;
        }

        public string GetPin()
        {
            string response = null;
            try
            {
                _initTemplate.GetElementsByTagName("ComPort")[0].InnerText = comNumStr;
                _initTemplate.GetElementsByTagName("Command")[0].InnerText = "ResetPinPad";
                response = PaymentEngine.DebitComChan.ProcessRequest(_initTemplate.InnerXml, PaymentEngine.CONST_NO_DIALOG);

                _getPinTemplate.GetElementsByTagName("ComPort")[0].InnerText = comNumStr;
                _getPinTemplate.GetElementsByTagName("Command")[0].InnerText = "GetPin";
                _getPinTemplate.GetElementsByTagName("AccountNo")[0].InnerText = AccountNo;
                _getPinTemplate.GetElementsByTagName("Timeout")[0].InnerText = Timeout;
                _getPinTemplate.GetElementsByTagName("Amount")[0].InnerText = Amount;
                response = PaymentEngine.DebitComChan.ProcessRequest(_getPinTemplate.InnerXml, PaymentEngine.CONST_NO_DIALOG);
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
            return response;
        }

        public static void Reset()
        {
            try
            {
                _initTemplate.GetElementsByTagName("ComPort")[0].InnerText = comNumStr;
                _initTemplate.GetElementsByTagName("Command")[0].InnerText = "ResetPinPad";
                PaymentEngine.DebitComChan.ProcessRequest(_initTemplate.InnerXml, PaymentEngine.CONST_NO_DIALOG);
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
        }

        public string Sale(MagneticCard mc)
        {
            string response = null;

            if (mc.TrackTwo == null)
            {
                throw new System.ArgumentNullException("Card Parameters contained Null Values");
            }
            else if (
                string.IsNullOrEmpty(InvoiceNo) ||
                string.IsNullOrEmpty(PINBlock) ||
                string.IsNullOrEmpty(DervdKey) ||
                string.IsNullOrEmpty(Purchase))
            {
                throw new System.ArgumentNullException("Function Parameters contained Null Values");
            }
            else
            {
                _transactionTemplate.GetElementsByTagName("IpAddress")[0].InnerText = IpAddress;
                _transactionTemplate.GetElementsByTagName("IpPort")[0].InnerText = IpPort;
                _transactionTemplate.GetElementsByTagName("MerchantID")[0].InnerText = PaymentEngine.MerchantId;
                _transactionTemplate.GetElementsByTagName("Memo")[0].InnerText = Oceanside.NotifyingSwRev.Swrev;
                //_transactionTemplate.GetElementsByTagName("TerminalID")[0].InnerText = PaymentEngine.GetTerminalId();
                _transactionTemplate.GetElementsByTagName("OperatorID")[0].InnerText = SHIFT.Current.User.Id.ToString();
                _transactionTemplate.GetElementsByTagName("TranType")[0].InnerText = "Debit";
                _transactionTemplate.GetElementsByTagName("Duplicate")[0].InnerText = PaymentEngine.AllowDuplicateOveride;
                _transactionTemplate.GetElementsByTagName("CardType")[0].InnerText = mc.CardType;
                _transactionTemplate.GetElementsByTagName("TranCode")[0].InnerText = "Sale";
                _transactionTemplate.GetElementsByTagName("InvoiceNo")[0].InnerText = InvoiceNo;
                _transactionTemplate.GetElementsByTagName("RefNo")[0].InnerText = RefNo;
                _transactionTemplate.GetElementsByTagName("Track2")[0].InnerText = mc.TrackTwo;
                _transactionTemplate.GetElementsByTagName("Purchase")[0].InnerText = Purchase;
                _transactionTemplate.GetElementsByTagName("SequenceNo")[0].InnerText = SequenceNo;
                _transactionTemplate.GetElementsByTagName("TerminalName")[0].InnerText = KIOSK.Get(SHIFT.GlobalContext).Name;
                _transactionTemplate.GetElementsByTagName("ShiftID")[0].InnerText = DAYPART.GetCurrDaypart(SHIFT.GlobalContext).Name;
                _transactionTemplate.GetElementsByTagName("Signature")[0].InnerText = Signature;
                _transactionTemplate.GetElementsByTagName("CashBack")[0].InnerText = CashBack;
                _transactionTemplate.GetElementsByTagName("PINBlock")[0].InnerText = PINBlock;
                _transactionTemplate.GetElementsByTagName("DervdKey")[0].InnerText = DervdKey;

                response =
                    PaymentEngine.CreditComChan.ProcessTransaction(
                    _transactionTemplate.InnerXml, PaymentEngine.CONST_NO_DIALOG, null, TraceData);
            }

            return response;
        }

        public string Return(MagneticCard mc)
        {
            string response = null;

            if (mc.TrackTwo == null)
            {
                throw new System.ArgumentNullException("Card Parameters contained Null Values");
            }
            else if (
                string.IsNullOrEmpty(InvoiceNo) ||
                string.IsNullOrEmpty(PINBlock) ||
                string.IsNullOrEmpty(DervdKey) ||
                string.IsNullOrEmpty(Purchase))
            {
                throw new System.ArgumentNullException("Function Parameters contained Null Values");
            }
            else
            {
                _transactionTemplate.GetElementsByTagName("IpAddress")[0].InnerText = IpAddress;
                _transactionTemplate.GetElementsByTagName("IpPort")[0].InnerText = IpPort;
                _transactionTemplate.GetElementsByTagName("MerchantID")[0].InnerText = PaymentEngine.MerchantId;
                _transactionTemplate.GetElementsByTagName("Memo")[0].InnerText = NotifyingSwRev.Swrev;
                //_transactionTemplate.GetElementsByTagName("TerminalID")[0].InnerText = PaymentEngine.GetTerminalId();
                _transactionTemplate.GetElementsByTagName("OperatorID")[0].InnerText = SHIFT.Current.User.Id.ToString();
                _transactionTemplate.GetElementsByTagName("TranType")[0].InnerText = "Debit";
                _transactionTemplate.GetElementsByTagName("Duplicate")[0].InnerText = PaymentEngine.AllowDuplicateOveride;
                _transactionTemplate.GetElementsByTagName("CardType")[0].InnerText = mc.CardType;
                _transactionTemplate.GetElementsByTagName("TranCode")[0].InnerText = "Return";
                _transactionTemplate.GetElementsByTagName("InvoiceNo")[0].InnerText = InvoiceNo;
                _transactionTemplate.GetElementsByTagName("RefNo")[0].InnerText = RefNo;
                _transactionTemplate.GetElementsByTagName("Track2")[0].InnerText = mc.TrackTwo;
                _transactionTemplate.GetElementsByTagName("Purchase")[0].InnerText = Purchase;
                _transactionTemplate.GetElementsByTagName("SequenceNo")[0].InnerText = SequenceNo;
                _transactionTemplate.GetElementsByTagName("TerminalName")[0].InnerText = KIOSK.Get(SHIFT.GlobalContext).Name;
                _transactionTemplate.GetElementsByTagName("ShiftID")[0].InnerText = DAYPART.GetCurrDaypart(SHIFT.GlobalContext).Name;
                _transactionTemplate.GetElementsByTagName("Signature")[0].InnerText = Signature;
                _transactionTemplate.GetElementsByTagName("PINBlock")[0].InnerText = PINBlock;
                _transactionTemplate.GetElementsByTagName("DervdKey")[0].InnerText = DervdKey;

                response =
                    PaymentEngine.CreditComChan.ProcessTransaction(
                    _transactionTemplate.InnerXml, PaymentEngine.CONST_NO_DIALOG, null, TraceData);
            }

            return response;
        }
    }
}
